$(document).ready(function(){
    laydate.skin('molv');/* 设置时间插件的皮肤 */
    var start = {
        elem: '#startTime', //选择ID为START的input
        format: 'YYYY-MM-DD', //自动生成的时间格式
        /*  min: laydate.now(), */ //设定最小日期为当前日期
        max: laydate.now(), //最大日期
        istoday: false,  //是否是当天
        start: laydate.now(0,"YYYY-MM-DD"),  //设置开始时间为当前时间
        choose: function(datas){
            over.min = datas; //开始日选好后，重置结束日的最小日期
            /*over.start = datas;*/ //将结束日的初始值设定为开始日
        }
    };
    var over = {
        elem: '#endTime',
        format: 'YYYY-MM-DD',
        max: laydate.now(),
        /* max: '2099-06-16 23:59:59',   */
        istoday: false,
        start: laydate.now(0,"YYYY-MM-DD"),
        choose: function(datas){
            start.max = datas; //结束日选好后，重置开始日的最大日期
        }
    };
    laydate(start);
    laydate(over);

    /*统计条件下拉框点击选项阻止收起事件*/
    $(".dropdown-menu").on("click","[data-stopPropagation]",function(e){
        e.stopPropagation();
    })
    var btnElement = '#SearchForm .dis';
    btnJurisdiction(btnElement);//查询当前用户的按钮权限

    turnType();            /*加载select下拉框数据*/
    loadBaseInfo();        /*获取当前用户有权限的基地数据*/
    loadEchartData();      /*调用加载图标方法*/
});

/*获取当前用户有权限的基地数据*/
function loadBaseInfo(){
    $.ajax({  //获取当前用户的基地权限
        type: "post",
        url: "../map/getBaseByUser",
        success: function (data) {
            if (data == "" || data == null) {  //如果当前用户没有基地权限时
                $('#baseTurn').html("");
            } else {
                /*加载搜索框内归属地下拉框数据*/
                var txt = '<option value="" selected="true">全部</option>';
                for (var i = 0; i < data.length; i++) {
                    txt += '<option  value="' + data[i].id + '">' + data[i].name + '</option>';
                }
                $('#baseTurn').html(txt);
                $('#baseTurn').selectpicker('refresh');
            }
        }
    });
}

/*获取工具类型、状态下拉框数据*/
function turnType(){
    $('#turnType').selectpicker('refresh');     //刷新下拉框
    $("#baseTurn").selectpicker('refresh');     //刷新下拉框
    /* 页面加载获取产品下拉框数据 */
    var tool_type = 'tool_type';
    var tool_status = 'tool_status';
    selecAjax(tool_type);
    selecAjax(tool_status);
}

/*调用后台接口获取select下拉框数据*/
function selecAjax(item){
    $.ajax({
        type: "POST",
        data:{
            parentcode:item,
            tool:'123'
        },
        async:true,
        url: '../sysCodeListController/getSysCodeList',
        success:function(res){
            var res = res.data;
            var txt ='<option value="" selected="true">全部</option>';
            var txt1 ='<option value="" selected="true">全部</option>';
            for(var i = 0;i <res.length;i++){
                if(res[i].parentcode == "tool_type"){
                    txt += '<option  value="' + res[i].id + '">' + res[i].name +'</option>';
                    $('#typeTurn').html(txt);
                    $('#typeTurn').selectpicker('refresh');
                }else if(res[i].parentcode == "tool_status"){
                    txt1 += '<option value="' + res[i].id + '">' + res[i].name +'</option>';
                    $('#statusTurn').html(txt1);
                    $('#statusTurn').selectpicker('refresh');
                }
            }
        }
    });
}

/*加载echarts图形*/
function loadEchartData(){
    var myChart = echarts.init(document.getElementById('main'));
    // 显示标题，图例和空的坐标轴
    myChart.setOption({
        title: {
            text: '丢失工具分析'
        },
        legend: {

        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow',
                label: {
                    show: true
                }
            }
        },

        calculable : true,
        grid: {
            top: '12%',
            left: '1%',
            right: '10%',
            containLabel: true
        },
        dataZoom : {
            show : true,
            realtime : true,
            start : 0,
            end : 100
        },
        xAxis: [{
            type: 'category',
            data:[],
            axisLabel:{
                show:true,
                rotate:0
            }
        }],
        yAxis: [{
            type:"value",
            name:"单位（个）",
            minInterval : 1,
            axisLabel : {
                formatter :  '{value}'
            },
            boundaryGap : [ 0, 0.1 ]
        }],
        color : ['#FFFF00','#FFA500', '#FF0000'],
        series: [
            {
                name: '低级',
                type: 'bar',
                barMaxWidth: '50',
                data: [],
                markPoint: {
                    data: [
                        {type: 'max', name: '最大值'},
                        {type: 'min', name: '最小值'}
                    ]
                },
                markLine: {
                    data: [
                        {type: 'average', name: '平均值'}
                    ]
                }
            },
            {
                name: '中级',
                type: 'bar',
                barMaxWidth: '50',
                data: [],
                markPoint: {
                    data: [
                        {type: 'max', name: '最大值'},
                        {type: 'min', name: '最小值'}
                    ]
                },
                markLine: {
                    data: [
                        {type: 'average', name: '平均值'}
                    ]
                }
            },
            {
                name: '高级',
                type: 'bar',
                barMaxWidth: '50',
                data: [],
                markPoint: {
                    data: [
                        {type: 'max', name: '最大值'},
                        {type: 'min', name: '最小值'}
                    ]
                },
                markLine: {
                    data: [
                        {type: 'average', name: '平均值'}
                    ]
                }
            }
        ]
    });

    var dataInfo = {};  //存放参数的空数组
    /*获取分析参数*/
    dataInfo.gsd = $('#SearchForm input[name="gsd"]:checked').val();
    if(dataInfo.gsd==null||dataInfo.gsd=="undefined"){
        dataInfo.gsd = "";
    }
    dataInfo.gjlx = $('#SearchForm input[name="gjlx"]:checked').val();
    if(dataInfo.gjlx==null||dataInfo.gjlx=="undefined"){
        dataInfo.gjlx = "";
    }
    dataInfo.gjmc = $('#SearchForm input[name="gjmc"]:checked').val();
    if(dataInfo.gjmc==null||dataInfo.gjmc=="undefined"){
        dataInfo.gjmc = "";
    }
    /*搜索条件参数*/
    var time = new Date();
    var timeDate = new Date(time).Format("hh:mm:ss");  //获取当前系统时间
    dataInfo.start = $("#startTime").val()==""?"":$("#startTime").val()+" 00:00:00";
    dataInfo.end = $("#endTime").val()==""?"":$("#endTime").val()+" "+timeDate;
    dataInfo.base = $("#baseTurn").val();
    dataInfo.type = $("#typeTurn").val();
    dataInfo.status = $("#statusTurn").val();
    dataInfo.toolName = $("#SearchForm input[name='toolName']").val();

    myChart.showLoading();    //数据加载完之前先显示一段简单的loading动画

    var names = [];    //类别数组（实际用来盛放X轴坐标值）
    var djInfo = [];   //低级滞留预警数据
    var zjInfo = [];   //中级级滞留预警数据
    var gjInfo = [];   //高级滞留预警数据
    $.ajax({
        type: "post",
        url: "../inspec/zlgjtj",
        data: dataInfo,
        dataType: "json",        //返回数据形式为json
        success: function (result) {
            //请求成功时执行该函数内容，result即为服务器返回的json对象
            if (result.length>0) {
                for (var i = 0; i < result.length; i++) {
                    //alert(result[i].name);
                    djInfo.push(result[i].djb);  //低级滞留预警数据
                    zjInfo.push(result[i].zjb);  //中级级滞留预警数据
                    gjInfo.push(result[i].gjb);  //高级滞留预警数据
                }
                for (var i = 0; i < result.length; i++) {
                    names.push(result[i].jbmc);    //挨个取出销量并填入销量数组
                }
                myChart.hideLoading();    //隐藏加载动画
                myChart.setOption({        //加载数据图表
                    toolbox: {
                        show : true,
                        feature : {
                            mark:{show:true},
                            magicType: {show: true, type: ['line', 'bar']},
                            restore : {show: true},
                            saveAsImage : {show: true},
                            myTool: {
                                show: true,
                                title: '打印',
                                icon: 'image://../img/print.png',
                                onclick: function (){
                                    var chartImg = $('#chartImg');
                                    chartImg.css('display','block');
                                    setTimeout(function(){
                                        var srcs = myChart.getDataURL({    //获取到当前生成数据的canvas图片地址
                                            pixelRatio: 1,
                                            backgroundColor: '#fff'
                                        });
                                        chartImg.attr("src",srcs);        // 将echart生成图片并放入img-box，并显示图片img-box
                                        $("#TestQuestions").jqprint({     // 打印
                                            debug:false,                 //如果是true则可以显示iframe查看效果（iframe默认高和宽都很小，可以再源码中调大），默认是false
                                            importCSS:true,              //true表示引进原来的页面的css，默认是true。（如果是true，先会找$("link[media=print]")，若没有会去找$("link")中的css文件）
                                            printContainer:true,         //表示如果原来选择的对象必须被纳入打印（注意：设置为false可能会打破你的CSS规则）。
                                            operaSupport:true            //表示如果插件也必须支持歌opera浏览器，在这种情况下，它提供了建立一个临时的打印选项卡。默认是true
                                        });
                                        chartImg.css('display','none');   // 执行打印后隐藏图片img-box
                                    },1000)
                                }
                            }
                        }
                    },
                    xAxis: [{
                        type: 'category',
                        name:'名称',
                        data:names,
                        axisLabel:{
                            show:true,
                            rotate:0
                        }
                    }],
                    yAxis: [{
                        type:"value",
                        name:"单位（个）",
                        minInterval : 1,
                        axisLabel : {
                            formatter :  '{value}'
                        },
                        boundaryGap : [ 0, 0.1 ]
                    }],
                    series: [
                        {
                            name: '低级',
                            type: 'bar',
                            data: djInfo
                        },
                        {
                            name: '中级',
                            type: 'bar',
                            data: zjInfo
                        },
                        {
                            name: '高级',
                            type: 'bar',
                            data: gjInfo
                        }
                    ]
                });

            }else{
                myChart.hideLoading();
                layer.msg("暂无数据");
            }

        },
        error: function (errorMsg) {
            //请求失败时执行该函数
            layer.msg("图表请求数据失败!");
            myChart.hideLoading();
        }
    })


}

/*点击分析按钮事件*/
function statInfo(){
    loadEchartData();
}

/*查询按钮点击事件*/
function searchdata(){
    loadEchartData();
}

// 对Date的扩展，将 Date 转化为指定格式的String
Date.prototype.Format = function (fmt) { //author: zhengsh 2016-9-5
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}


function Base64() {

    // private property
    _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

    // public method for encoding
    this.encode = function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;
        input = _utf8_encode(input);
        while (i < input.length) {
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);
            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;
            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }
            output = output +
                _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
                _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
        }
        return output;
    }

    // public method for decoding
    this.decode = function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
        while (i < input.length) {
            enc1 = _keyStr.indexOf(input.charAt(i++));
            enc2 = _keyStr.indexOf(input.charAt(i++));
            enc3 = _keyStr.indexOf(input.charAt(i++));
            enc4 = _keyStr.indexOf(input.charAt(i++));
            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;
            output = output + String.fromCharCode(chr1);
            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }
        }
        output = _utf8_decode(output);
        return output;
    }

    // private method for UTF-8 encoding
    _utf8_encode = function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";
        for (var n = 0; n < string.length; n++) {
            var c = string.charCodeAt(n);
            if (c < 128) {
                utftext += String.fromCharCode(c);
            } else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            } else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }
        return utftext;
    }

    // private method for UTF-8 decoding
    _utf8_decode = function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;
        while ( i < utftext.length ) {
            c = utftext.charCodeAt(i);
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            } else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            } else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    }
}